import React, { Component } from "react"
/*
  祖孙组件间传递数据
*/

// 创建Context对象
const MyContext = React.createContext()
const { Provider, Consumer } = MyContext

export default class Context extends Component {
  /*
        Context 适用于祖组件和后代组件之间的通信
      */
  state = { name: "qwe", age: 14 }
  render() {
    const { name, age } = this.state
    return (
      <h1>
        Context----{name}
        {age}
        <Provider value={{ name, age }}>
          {/* 不允许改名 只能叫value */}
          <A></A>
        </Provider>
      </h1>
    )
  }
}

class A extends Component {
  render() {
    return (
      <h1>
        A<B></B>
      </h1>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div>
        B<C></C>
      </div>
    )
  }
}

class C extends Component {
  static contextType = MyContext
  //  要声明接收才能收到 只能类适用
  render() {
    console.log(this.context)
    const { name, age } = this.context

    return (
      <div>
        C-----接收的用户名：{name}
        {age}
        <D></D>
      </div>
    )
  }
}
function D() {
  return (
    <div>
      D-----接收的用户名：
      <Consumer>
        {/* 类组件和函数组件都适用 */}
        {(value) => {
          return `${value.name}${value.age}`
        }}
      </Consumer>
    </div>
  )
}
